package cn.rongcloud.im.ui.activity;

import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import com.mbt.im.R;

import cn.rongcloud.im.SealAppContext;
import cn.rongcloud.im.SealUserInfoManager;
import cn.rongcloud.im.db.Friend;
import cn.rongcloud.im.server.broadcast.BroadcastManager;
import cn.rongcloud.im.server.network.http.HttpException;
import cn.rongcloud.im.server.pinyin.CharacterParser;
import cn.rongcloud.im.server.response.BaseResponse;
import cn.rongcloud.im.server.response.FriendRemarkResponse;
import cn.rongcloud.im.server.response.SetFriendDisplayNameResponse;
import cn.rongcloud.im.server.utils.NToast;
import cn.rongcloud.im.server.widget.LoadDialog;
import cn.rongcloud.im.ui.activity.base.BaseActivity;
import io.rong.imkit.RongIM;
import io.rong.imlib.model.UserInfo;

/**
 * 设置备注
 */
@SuppressWarnings("deprecation")
public class NoteInformationActivity extends BaseActivity {

    private static final int SET_DISPLAYNAME = 12;
    private static final int SELECT_FRIEND_REMARK = 13;
    private static final int SET_FRIEND_REMARK = 14;
    private Friend mFriend;
    private EditText mNoteEdit;
    private TextView mNoteSave;
    private static final int CLICK_CONTACT_FRAGMENT_FRIEND = 2;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_noteinfo);
//        setHeadVisibility(View.GONE);
        setTitle(R.string.ac_note_info);
        mNoteEdit = (EditText) findViewById(R.id.notetext);
        mNoteSave = (TextView) findViewById(R.id.notesave);
        mFriend = getIntent().getParcelableExtra("friend");
        if (mFriend != null) {
//            mNoteSave.setOnClickListener(new View.OnClickListener() {
//                @Override
//                public void onClick(View v) {
//                    LoadDialog.show(mContext);
//                    request(SET_DISPLAYNAME);
//                }
//            });
//            mNoteSave.setClickable(false);

            Button rightButton = getHeadRightButton();
            rightButton.setVisibility(View.GONE);
            mHeadRightText.setVisibility(View.VISIBLE);
            mHeadRightText.setText(R.string.de_save);
            mHeadRightText.setTextColor(getResources().getColor(R.color.title_bar_right_color));
            mHeadRightText.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    LoadDialog.show(mContext);
                    request(SET_FRIEND_REMARK);
                }
            });
            mHeadRightText.setClickable(false);


            mNoteEdit.setText(mFriend.getDisplayName());
            mNoteEdit.setSelection(mNoteEdit.getText().length());
            mNoteEdit.addTextChangedListener(new TextWatcher() {
                @Override
                public void beforeTextChanged(CharSequence s, int start, int count, int after) {

                }

                @Override
                public void onTextChanged(CharSequence s, int start, int before, int count) {
                    if (!TextUtils.isEmpty(mFriend.getDisplayName())) {
                        mHeadRightText.setClickable(true);
                        mHeadRightText.setTextColor(getResources().getColor(R.color.white));
                    } else {
                        if (TextUtils.isEmpty(s.toString())) {
                            mHeadRightText.setClickable(false);
                            mHeadRightText.setTextColor(Color.parseColor("#9fcdfd"));
                        } else if (s.toString().equals(mFriend.getDisplayName())) {
                            mHeadRightText.setClickable(false);
                            mHeadRightText.setTextColor(Color.parseColor("#9fcdfd"));
                        } else {
                            mHeadRightText.setClickable(true);
                            mHeadRightText.setTextColor(getResources().getColor(R.color.white));
                        }
                    }

                }

                @Override
                public void afterTextChanged(Editable s) {

                }
            });

            request(SELECT_FRIEND_REMARK);

        }
    }

    @Override
    public Object doInBackground(int requestCode, String id) throws HttpException {
        switch (requestCode) {
            case SET_DISPLAYNAME:
                return action.setFriendDisplayName(mFriend.getUserId(), mNoteEdit.getText().toString().trim());
            case SELECT_FRIEND_REMARK:
                return action.selectFriendRemark(mFriend.getUserId());
            case SET_FRIEND_REMARK:
                return action.setFriendRemark(mFriend.getUserId(), mNoteEdit.getText().toString().trim());
        }
        return super.doInBackground(requestCode, id);
    }

    @Override
    public void onSuccess(int requestCode, Object result) {
        if (result != null) {
            switch (requestCode) {
                case SET_DISPLAYNAME:
                    SetFriendDisplayNameResponse response = (SetFriendDisplayNameResponse) result;
                    if (response.getCode() == 200) {
                        setRemarkName();
                    }
                    break;
                case SELECT_FRIEND_REMARK:
                    FriendRemarkResponse response2 = (FriendRemarkResponse) result;
                    if (response2.getResultCode() == 0) {
                        if (response2.getData() == null) return;
                        if (TextUtils.isEmpty(response2.getData().getFriendRemark()))
                            mNoteEdit.setText(response2.getData().getName());
                        else
                            mNoteEdit.setText(response2.getData().getFriendRemark());

                        mNoteEdit.setSelection(mNoteEdit.getText().toString().length());
                    }
                    break;
                case SET_FRIEND_REMARK:
                    BaseResponse response3 = (BaseResponse) result;
                    if (response3.getResultCode() == 0) {
                        NToast.shortToast(mContext, response3.getMsg());
                        setRemarkName();
                    }
                    break;
            }
        }
    }

    private void setRemarkName() {
        String displayName = mNoteEdit.getText().toString();
        if (displayName != null) {
            displayName = displayName.trim();
        }
        SealUserInfoManager.getInstance().addFriend(
                new Friend(mFriend.getUserId(),
                        mFriend.getName(),
                        mFriend.getPortraitUri(),
                        displayName,
                        null, null,
                        mFriend.getStatus(),
                        mFriend.getTimestamp(),
                        CharacterParser.getInstance().getSpelling(mFriend.getName()),
                        CharacterParser.getInstance().getSpelling(displayName)));
        if (TextUtils.isEmpty(displayName)) {
            RongIM.getInstance().refreshUserInfoCache(new UserInfo(mFriend.getUserId(), mFriend.getName(), mFriend.getPortraitUri()));
        } else {
            RongIM.getInstance().refreshUserInfoCache(new UserInfo(mFriend.getUserId(), displayName, mFriend.getPortraitUri()));
        }
        BroadcastManager.getInstance(mContext).sendBroadcast(SealAppContext.UPDATE_FRIEND);
        Intent intent = new Intent(mContext, UserDetailActivity.class);
        intent.putExtra("type", CLICK_CONTACT_FRAGMENT_FRIEND);
        intent.putExtra("displayName", mNoteEdit.getText().toString().trim());
        setResult(155, intent);
        LoadDialog.dismiss(mContext);
        finish();
    }

    @Override
    public void onFailure(int requestCode, int state, Object result) {
        if (requestCode == SET_DISPLAYNAME) {
            LoadDialog.dismiss(mContext);
        }
        super.onFailure(requestCode, state, result);
    }

    public void finishPage(View view) {
        this.finish();
    }
}
